package com.qixia.sportsupload.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Description: 校验身份证
 * @Author: liufei
 * @Date: 2021-11-5 0005
 **/
public class IdCardValidatorUtilNew {
    public static boolean isValidatedAllIdcard(String idCard) {
        String regex = "(11|12|13|14|15|21|22|23|31|32|33|34|35|36|37|41|42|43|44|45|46|50|51|52|53|54|61|62|63|64|65|71|81|82)[0-9]{15}([0-9xX])";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(idCard);
        return matcher.matches();
    }

    public static String getSexFromIdCard(String idCard){
        String sex = "";
        int index = idCard.length() - 2;
        // 判断性别
        if (Integer.parseInt(idCard.substring(index).substring(0, 1)) % 2 == 0) {
            sex = "0";
        } else {
            sex = "1";
        }
        return sex;
    }

    public static String getBirthday(String idCard) {
        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyyMMdd");
        SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd");
        try {
            return simpleDateFormat2.format(simpleDateFormat1.parse(idCard.substring(6,14)));
        } catch (ParseException e) {
            return "";
        }
    }

    public static String getAge(String idCard) {
        Calendar calendar = Calendar.getInstance();
        int currentYear = calendar.get(Calendar.YEAR);
        // 提取身份证号中的出生日期
        String birthDateStr = idCard.substring(6, 14);
        // 将出生日期字符串转换为Date类型
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        Date birthDate = null;
        try {
            birthDate = dateFormat.parse(birthDateStr);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        // 计算年龄
        calendar.setTime(birthDate);
        int birthYear = calendar.get(Calendar.YEAR);
        int age = currentYear - birthYear;
        return String.valueOf(age);
    }
}
